<template>
	<div class="jim">
		<header class="cxo-red layout lh100 fixed-t">
			<i class="iconfont icon-zuo white ml30rem" style="font-size:1.6rem" @click="$router.back('-1')"></i>
			<h3 class="white align-center" style="position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);">{{ serviceName }}</h3>
		</header>

		<section class="mt100rem" style="margin-bottom:4.5rem;height: 40rem;overflow-x: scroll;" id='adc'>
			<loadmore ref="loadmore" :top-method="getRecord" :bottom-all-loaded="allLoaded">
				<div class="content" v-for="item of msgs" v-if="msgs.length > 0">
					<p class="align-center pt40rem"><span class="bg-ccc circle-8 pl10rem pr10rem white">{{ item.msg_ctime,'MM-dd hh:mm' | formatDate }}</span></p>
					<div class="content-text layout flex-left auto" style="width:92%" v-if="item.self">
						<img src="../../assets/logo-img.png" alt="" class="img circle mr20rem" >
						<img class="border" style="width:6rem;height:8rem;object-fit:cover;" v-if="item.msg_type=='image'" :src="item.msg_body
	" alt="">
						<p class="right-p bg-f5 pt30rem pb30rem pr25rem pl25rem circle-8" style="line-height:150%;" v-else>{{ item.msg_body }}</p>
					</div>
					<div class="layout flex-right pt40rem auto" style="width:92%" v-else>
						<div class="flex-right">
							<span class="cxo-red-color flex-end mr10rem fs14rem" v-if="false">未读</span>
							<span class="c999 flex-end mr10rem fs14rem" v-else>已读</span>
							<img class="border" style="width:6rem;height:8rem;object-fit:cover;" v-if="item.msg_type=='image'" :src="item.msg_body" alt="">
							<p class="right-p bg-f5 pt30rem pb30rem pr25rem pl25rem circle-8" style="line-height:150%;" v-else>{{ item.msg_body }}</p>
						</div>
						<img src="../../assets/logo-img.png" alt="" class="img circle ml20rem" >
					</div>
				</div>
			</loadmore>
		</section>
		<footer class="footer fixed-b bg-f5 pt20rem pb20rem"> 
			<div class="w92 layout auto">
				<input type="text" class="bg-white mr30rem ml30rem border circle-8 flex_1 pl20rem" @keyup.enter="send" v-model="inputContent" placeholder="请输入内容...">
				<button class="white cxo-red circle-8 pt15rem pb15rem pl30rem pr30rem fs30rem" @click="send" v-if="inputContent">发送</button>
				<button class="" v-else @click="funcShow = !funcShow"><i class="iconfont icon-jia fs40rem pt20rem pb20rem pl20rem pr20rem fs30rem"></i></button>
			</div>
			<div class="w92 flex-left auto" v-show="funcShow">
				<div class="align-center mt30rem ml30rem mr30rem" @click="uploadImg">
					<input type="file" id="file_box" @change="File" style="display: none;">
					<img src="../../assets/icon13.png" alt="" style="width:30px;">
					<p>相册</p>
				</div>
			</div>
		</footer>
	</div>
</template>

<script>
import { getHistory } from "@/api/jim";
import md5 from 'js-md5';
import { Loadmore } from 'mint-ui';
import { formatDate,loginJIM } from "@/utils";
export default{
	components:{
		Loadmore
	},
	filters: {
		formatDate(time,fmt){
			let date = new Date(time);
			return formatDate(date,fmt);
		}
  	},
	data()
	{
		return{
			username        : window.sessionStorage.getItem('username'),
			showApp         : window.sessionStorage.getItem('isapp'),
			msgs            : [],
			oContent        : {},
			serviceName     : '在线客服',
			serviceImg      : '',
			serviceAppkey   : '',
			inputContent    : "",
			funcShow        : false,
			allLoaded       : false,
			unread_count    : '',
			page            : 1,
			
		}
	},
	updated:function(){
	    this.$nextTick(()=>{
	    	var div = document.getElementById('adc');
	        div.scrollTop = div.scrollHeight;
	    })
    },
	created()
	{
		loginJIM(window.localStorage.getItem('mobile'),'jiguang520');
		// this.getRecord();
		// this.getService();
		// 聊天消息
		// JIM.onMsgReceive(res => {
		// 	if(res.messages[0].content.msg_type == 'image')
		// 	{
		// 		JIM.getResource({
		//             'media_id' : res.messages[0].content.msg_body.media_id //构造好的 FormData
  //               }).onSuccess(data => {
	 //                this.msgs.push({
		// 				msg_body :  data.url,
		// 				msg_type : 'image',
		// 				self     : true,
		// 				msg_ctime     : res.messages[0].content.create_time
	 //                })
	 //            })
		// 	}
		// 	else{
		// 		this.msgs.push({
		// 			msg_body : res.messages[0].content.msg_body.text,
		// 			self     : true,
		// 			msg_ctime     : res.messages[0].content.create_time
		// 		})
		// 	}
		// });
	},
	methods:
	{
		send(){
			// 发送消息
			if(!this.inputContent) return;

			JIM.sendSingleMsg({
				'target_username' : this.$route.query.nickname,
				'content'         : this.inputContent,
				'msg_body'        : this.inputContent,
				'need_receipt'    : true
			}).onSuccess((res,msg) => {
				console.log(msg)
				this.msgs.push({
					msg_body  : msg.content.msg_body.text,
					self      : false,
					msg_ctime : res.messages[0].content.create_time
				})
				// 聊天实时监听
				JIM.onMsgReceive(res => {
					console.log(res)
					if(res.messages[0].content.msg_type == 'image')
					{
						JIM.getResource({
				            'media_id' : res.messages[0].content.msg_body.media_id //构造好的 FormData
		                }).onSuccess(res => {
		                	this.funcShow = false;
			                this.msgs.push({
								img      :  res.url,
								msg_type : 'image',
								self     : true,
								msg_ctime     : res.messages[0].content.create_time
			                })
			            }).onFail(function(data) {

			           	});
					}
					else{
						this.msgs.push({
							msg_body : res.messages[0].content.msg_body.text,
							self     : true,
							msg_ctime     : res.messages[0].content.create_time
						})
					}
				})
			    // do something
			})
           	this.inputContent = '';
		},
		getService()
		{
			// 获取用户信息
			JIM.getUserInfo({
		        'username' : this.$route.query.nickname,
	        }).onSuccess(res => {
	        	this.serviceName = res.user_info.nickname;
	        	this.serviceImg = res.user_info.avatar;
	        	this.serviceAppkey = res.user_info.appkey;
	        }).onFail(res => {
	            //res.code 返回码
	            //res.message 描述
	        });
		},
		uploadImg()
		{
			document.getElementById('file_box').click();
		},
		File(){
			this.sendSinglePic();
		},
		// 发送图片
	 	sendSinglePic() {
	        JIM.sendSinglePic({
				'target_username' : this.$route.query.nickname,
				'target_nickname' : this.serviceName,
				'appkey'          : this.serviceAppkey,
				'image'           : this.getFile(),
				'nead_receipt'    : true
            }).onSuccess((res,msg) => {
            	// 获取图片
                JIM.getResource({
		            'media_id' : msg.content.msg_body.media_id //构造好的 FormData
                }).onSuccess(res => {
                	this.funcShow = false;
	                this.msgs.push({
						msg_body :  res.url,
						msg_type : 'image',
						time     : res.messages[0].content.create_time
	                })
	            })
            }).onFail(function(res) {
                console.log('error:' + JSON.stringify(res))
           	});
	    },
		getFile() {
	    	var fd = new FormData();
	        var file = document.getElementById('file_box');
	        if(!file.files[0]) {
	            throw new Error('获取文件失败');
	        }
	        fd.append(file.files[0].name, file.files[0]);
	        return fd;
	    },

	    getRecord()
	    {
	    	console.log(this.username)
	    	let params = {
				user_name : this.username,
				page      : this.page++,
				item      : 10
	    	}
			getHistory(params).then(res => {


				if( res.data.length > 0 )
				{ 
					this.msgs = res.data;
				}
				else if (params.page > 1)
				{
					this.allLoaded = true;
				}
				else
				{
					this.allLoaded = true;
				}
				if( res.data.length < params.item )
				{
					this.allLoaded = true;
				}
			 	this.$refs.loadmore.onTopLoaded();
			})
	    }
	}
}
</script>

<style lang="less">
.jim{
	.content{
		.img{
			width: 80/28rem;
		}
		.left-p{
			position: relative;
		}
		.left-p:before {
			content:'';
			border-top: 15/28rem solid transparent;
		    border-left: 15/28rem solid transparent;
		    border-right: 15/28rem solid #f5f5f5;;
		    border-bottom: 15/28rem solid transparent;
		    color: #f5f5f5;
		    width:0;
		    height:0;
		    display: inline-block;
		    position: absolute;
		    left: -25/28rem;;
		    top: 40%;
		}
		.right-p{
			position: relative;
		}
		.right-p:before {
			content:'';
			border-top: 15/28rem solid transparent;
		    border-left: 15/28rem solid #f5f5f5;
		    border-right: 15/28rem solid transparent;
		    border-bottom: 15/28rem solid transparent;
		    color: #f5f5f5;
		    width:0;
		    height:0;
		    display: inline-block;
		    position: absolute;
		    right: -25/28rem;
		    top: 40%;
		}
	}
	.footer{
		input{
			height: 65/28rem;
			line-height: 65/28rem;
		}
	}
}
</style>
